<script setup lang="ts">
import * as echarts from 'echarts'
import {onMounted, ref} from "vue";

let chartRef = ref()
let chart: echarts.ECharts

onMounted(() => {
  chart = echarts.init(chartRef.value)
  chart.setOption(option)
})

window.addEventListener("resize", () => {
  chart.resize();
})

function updateData(): void {
  chart.setOption({
    xAxis: {
      data: props.chartData.xData
    },
    series: [
      {
        data: props.chartData.seriesData
      }
    ]
  });
}

defineExpose({
  updateData
})

export interface ChartData {
  title: string,
  xData: string[],
  seriesData: number[],
  seriesName: string,
  itemColor: string
}

const props = defineProps({
  chartData: {
    type: Object as () => ChartData,
    required: true
  }
})

const option: echarts.EChartsOption = {
  tooltip: {
    trigger: 'axis',
    position: function (pt) {
      return [pt[0], '10%'];
    }
  },
  title: {
    text: props.chartData.title
  },
  xAxis: {
    type: 'category',
    data: props.chartData.xData
  },
  yAxis: {
    type: 'value',
    minInterval: 1
  },
  series: [
    {
      name: props.chartData.seriesName,
      data: props.chartData.seriesData,
      type: 'line',
      symbol: 'none',
      step: 'start',
      itemStyle: {
        color: props.chartData.itemColor
      }
    }
  ]
}
</script>

<template>
  <div class="echarts" ref="chartRef"></div>
</template>

<style scoped>
.echarts {
  width: 100%;
  height: 40vh;
}
</style>